package weekMatch.one_342;

import java.awt.peer.CanvasPeer;
import java.util.*;

public class LeeCode_03 {
    public static void main(String[] args) {
//        System.out.println(Arrays.toString(getSubarrayBeauty(new int[]{1, -1, -3, -2, 3}, 3, 2)));
//        System.out.println(Arrays.toString(getSubarrayBeauty(new int[]{5}, 1, 1)));
        System.out.println(Arrays.toString(getSubarrayBeauty(new int[]{-46, -34, -46}, 3, 3)));
    }
    private static int[] getSubarrayBeauty(int[] nums, int k, int x) {
        int n = nums.length;
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < k; i++) {
            if (map.containsKey(nums[i])){
                map.put(nums[i], map.get(nums[i]) + 1);
            }else {
                map.put(nums[i], 1);
            }
        }
        int l = 1, r = l + k - 1;
        int[] ans = new int[n - k + 1];
        Set<Integer> set = map.keySet();
        int count = 0;
        int index = 0;
        for (Integer key : set) {
            int c = map.get(key);
            count += c;
            if (count >= x){
                ans[index++] = Math.min(0, key);
                break;
            }
        }
        while (r < n){
            if (map.get(nums[l - 1]) == 1){
                map.remove(nums[l - 1]);
            }else {
                map.put(nums[l - 1], map.get(nums[l - 1]) - 1);
            }
            if (map.containsKey(nums[r])){
                map.put(nums[r], map.get(nums[r]) + 1);
            }else {
                map.put(nums[r], 1);
            }
            count = 0;
            for (Integer key : set) {
                int c = map.get(key);
                count += c;
                if (count >= x){
                    ans[index++] = Math.min(0, key);
                    break;
                }
            }
            l++;
            r++;
        }
        return ans;
    }
}
